import { useState, useEffect } from "react";
import { Table } from "antd";

function List() {
  const [dataSource, setDataSource] = useState([]);

  const columns = [
    {
      title: "主机",
      dataIndex: "Host",
      align: "center",
      className: "bgGray",
    },
    {
      title: "节点",
      dataIndex: "Node",
      align: "center",
      className: "bgGray",
    },
    {
      title: "最大延迟[ms]",
      dataIndex: "MaxDelay",
      align: "center",
      className: "bgGray",
    },
    {
      title: "平均延迟[ms]",
      dataIndex: "AvgDelay",
      align: "center",
      className: "bgGray",
    },
    {
      title: "最小延迟[ms]",
      dataIndex: "MinDelay",
      align: "center",
      className: "bgGray",
    },
    {
      title: "丢包率[%]",
      dataIndex: "LossPk",
      align: "center",
      className: "bgGray",
    },
  ];

  const rowClassName = (r) => {
    if (r.LossPk == 0) {
      return "bgGreen";
    } else if (r.LossPk < 100) {
      return "bgYellow";
    } else {
      return "bgRed";
    }
  };

  const drawTable = (host) => {
    let rowIndex = 0;
    let rows = [];
    let hostName = `${host.Name}[${host.Ip}]`;
    for (let intf of host.Interfaces) {
      for (let ip in intf.PingStatus) {
        let status = intf.PingStatus[ip];
        let row = {
          key: rowIndex++,
          Host: hostName,
          Node: ip,
          MaxDelay: status.MaxDelay | 0,
          AvgDelay: status.AvgDelay | 0,
          MinDelay: status.MinDelay | 0,
          LossPk: status.LossPk,
        };
        rows.push(row);
      }
    }

    rows.sort((a, b) => {
      return (a.LossPk - b.LossPk) | (a.AvgDelay - b.AvgDelay);
    });

    setDataSource(rows);
  };

  const fetchHosts = async () => {
    const res = await fetch("/api/host.json");
    if (res.ok) {
      const host = await res.json();
      drawTable(host);
    }
  };

  useEffect(() => {
    let intervalId = null;
    fetchHosts();

    intervalId = setInterval(() => {
      fetchHosts();
    }, 60000);

    return () => clearInterval(intervalId);
  }, []);

  return (
    <>
      <Table
        dataSource={dataSource}
        columns={columns}
        rowClassName={rowClassName}
        pagination={false}
      />
      ;
    </>
  );
}

export default List;
